﻿using System;
using System.Linq;
using System.Reflection;
using Furion.DependencyInjection;
using SqlSugar;
using Vboot.Core.Common;
using Vboot.Core.Module.Sys;

namespace Vboot.Web.Core.Init
{
    public class DbSeedService : IScoped
    {
        private readonly ISqlSugarRepository<SysOrg> _repo;

        private readonly DbInitListener _dbInitListener;


        public DbSeedService(ISqlSugarRepository<SysOrg> repo
            , DbInitListener dbInitListener)
        {
            _repo = repo;
            _dbInitListener = dbInitListener;
        }


        public async void Init()
        {
            var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
            // // core表自动生成
            var coreAssemblies = System.IO.Directory.GetFiles(path, "Vboot.Core.dll").Select(Assembly.LoadFrom)
                .ToArray();
            
            var coreModelTypes = coreAssemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(x => x.IsClass && x.Namespace != null && x.Namespace.StartsWith("Vboot")).ToList();
            coreModelTypes.ForEach(t =>
            {
                var customAttributeDatas = t.CustomAttributes;
                foreach (var attribute in customAttributeDatas)
                {
                    if (attribute.ToString().Contains("SugarTable"))
                    {
                        _repo.Context.CodeFirst.InitTables(t);
                        Console.WriteLine(attribute);
                    }
                }
            });
            
            var appAssemblies = System.IO.Directory.GetFiles(path, "Vboot.Application.dll").Select(Assembly.LoadFrom)
                .ToArray();
            
            var appModelTypes = appAssemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(x => x.IsClass && x.Namespace != null && x.Namespace.StartsWith("Vboot")).ToList();
            appModelTypes.ForEach(t =>
            {
                var customAttributeDatas = t.CustomAttributes;
                foreach (var attribute in customAttributeDatas)
                {
                    if (attribute.ToString().Contains("SugarTable"))
                    {
                        _repo.Context.CodeFirst.InitTables(t);
                        Console.WriteLine(attribute);
                    }
                }
            });

            await _dbInitListener.Init();


            // repo.Context.CodeFirst.InitTables(typeof(SysOrg));
            // repo.Context.CodeFirst.InitTables(typeof(SysOrgUser));
        }
    }
}